package edu.langnan.xiaoli.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.langnan.xiaoli.core.dto.WeiXinLoginResultDTO;
import edu.langnan.xiaoli.exception.CustomException;
import edu.langnan.xiaoli.exception.user.UserPasswordNotMatchException;
import edu.langnan.xiaoli.service.StudentService;
import edu.langnan.xiaoli.service.WeiXinService;
import edu.langnan.xiaoli.utils.StringUtils;
import edu.langnan.xiaoli.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;

/**
 * @author cql
 */
@Service
public class WeiXinServiceImpl implements WeiXinService {

    private static final Logger log = LoggerFactory.getLogger(WeiXinService.class);


    private static final String AUTH_CODE2SESSION = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";

    @Value("${weixin.AppSecret}")
    private String appSecret;

    @Value("${weixin.AppID}")
    private String appID;

    @Override
    public WeiXinLoginResultDTO weiXinLogin(String code) {
        if (StringUtils.isEmpty(code)) {
            throw new UserPasswordNotMatchException();
        }
        String url = MessageFormat.format(AUTH_CODE2SESSION, appID, appSecret, code);
        String str = HttpUtils.sendGet(url);
        ObjectMapper objectMapper = new ObjectMapper();
        WeiXinLoginResultDTO result = null;
        try {
            result = objectMapper.readValue(str, WeiXinLoginResultDTO.class);
            if (StringUtils.isEmpty(result.getOpenid())) {
                throw new CustomException(result.getErrmsg());
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        return result;
    }


}
